﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
using System.IO;

namespace ImPM.Application
{
    public class ImPMTraceSettings
    {
        // Fields
        private int _fileCountSuffix;
        private string _fileName;
        private ImPMTrace.TraceBool _isTracingOff;
        private ImPMTrace.LoadStatus _loadState;
        private int _refreshTraceInt;
        private SettingsPrecedence _settingsPrecedence;
        private Hashtable _traceCategoryLevels;
        private string _traceDirectory;
        private int _traceFileSize;
        private ImPMTrace.TraceBool _tracingCallStack;
        private static ImPMTraceSettings deploymentSettings;
        private static ImPMTraceSettings localServerRegistrySettings;
        private static Dictionary<Guid, ImPMTraceSettings> orgSettings = new Dictionary<Guid, ImPMTraceSettings>();
        internal static ReaderWriterLock orgSettingsLock = new ReaderWriterLock();
        internal static ReaderWriterLock readerWriterLock = new ReaderWriterLock();
        private static ImPMTraceSettings siteWideSettings;
        private static volatile TextWriter writer = null;

        // Methods
        public ImPMTraceSettings()
        {
            this._traceFileSize = 0xa00000;
            this._refreshTraceInt = -1;
            this.LoadState = ImPMTrace.LoadStatus.NotLoaded;
        }

        public ImPMTraceSettings(int fileCountSuffix, Guid orgId)
        {
            this._traceFileSize = 0xa00000;
            this._refreshTraceInt = -1;
            ImPMTrace.TraceDisabled = true;
            try
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                ImPMTrace.TraceDisabled = false;
            }
            if ((this.IsTracingOff != ImPMTrace.TraceBool.No) || (this.TraceDirectory == null))
            {
                this.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulUnreported;
            }
            else
            {
                try
                {
                    this.FileName = GetFileName(this.TraceFileSize, ref fileCountSuffix, this.TraceDirectory);
                }
                catch (Exception)
                {
                }
                finally
                {
                    ImPMTrace.TraceDisabled = false;
                }
                if ((this.IsTracingOff != ImPMTrace.TraceBool.No) || (this.TraceDirectory == null))
                {
                    this.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulUnreported;
                }
                else
                {
                    using (new ImPMLock(readerWriterLock, LockMode.Write))
                    {
                    }
                    this.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulUnreported;
                }
            }
        }

        public static ImPMTraceSettings ChangeFileName(ImPMTraceSettings oldSettings, int fileCountSuffix)
        {
            ImPMTraceSettings settings = new ImPMTraceSettings();
            settings.TraceDirectory = oldSettings.TraceDirectory;
            settings._traceCategoryLevels = oldSettings._traceCategoryLevels;
            settings.TraceFileSize = oldSettings.TraceFileSize;
            settings.TracingCallStack = oldSettings.TracingCallStack;
            settings.RefreshTraceInt = oldSettings.RefreshTraceInt;
            settings.FileCountSuffix = fileCountSuffix;
            settings.IsTracingOff = ImPMTrace.TraceBool.No;
            int num = settings.FileCountSuffix;
            try
            {
                settings.FileName = GetFileName(settings.TraceFileSize, ref num, settings.TraceDirectory);
            }
            catch (InvalidOperationException)
            {
                settings.IsTracingOff = ImPMTrace.TraceBool.Yes;
            }
            settings.FileCountSuffix = num;
            using (new ImPMLock(readerWriterLock, LockMode.Write))
            {
            }
            settings.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulUnreported;
            return settings;
        }

        private static Hashtable GenerateTraceCategories(string traceCategoriesUnsplit)
        {
            ArrayList rulePairs = new ArrayList();
            ArrayList list2 = new ArrayList();
            ArrayList list3 = new ArrayList();
            Hashtable categoryHash = new Hashtable();
            char[] separator = new char[] { ';' };
            char[] chArray2 = new char[] { ':' };
            string[] strArray = traceCategoriesUnsplit.Split(separator);
            string[] strArray2 = null;
            foreach (string str in strArray)
            {
                strArray2 = str.Split(chArray2);
                if (strArray2.Length != 0)
                {
                    if (strArray2.Length != 2)
                    {
                        ImPMTrace.WriteEventError(0xc0004301L, new string[] { str });
                        return null;
                    }
                    strArray2[0] = strArray2[0].Trim();
                    strArray2[1] = strArray2[1].Trim();
                    if (strArray2[0].Equals("*"))
                    {
                        list3.Add(strArray2);
                    }
                    else if (strArray2[0].EndsWith(".*"))
                    {
                        list2.Add(strArray2);
                    }
                    else
                    {
                        rulePairs.Add(strArray2);
                    }
                }
            }
            if (list3.Count == 0)
            {
                list3.Add(new string[] { "*", "Off" });
            }
            if (!ImPMTrace.InsertCategoriesIntoHashtable(rulePairs, categoryHash))
            {
                return null;
            }
            if (!ImPMTrace.InsertSubcategoriesIntoHashtable(list2, categoryHash))
            {
                return null;
            }
            if (!ImPMTrace.InsertAllCategoriesIntoHashtable(list3, categoryHash))
            {
                return null;
            }
            return categoryHash;
        }

        private static string GetFileName(int traceFileSize, ref int fileCountSuffix, string traceDirectory)
        {
            string fileName = ImPMTrace.GetFileName(true, fileCountSuffix, traceDirectory);
            if (fileName == null)
            {
                throw new InvalidOperationException("Trace Directory not defined");
            }
            ImPMTrace.FileChange none = ImPMTrace.FileChange.None;
            while (none != ImPMTrace.FileChange.KeepCurrent)
            {
                fileName = ImPMTrace.GetFileName(true, fileCountSuffix, traceDirectory);
                switch (ImPMTrace.GetFileChange(fileName, traceFileSize, fileCountSuffix, traceDirectory))
                {
                    case ImPMTrace.FileChange.Error:
                        throw new InvalidOperationException("Error accessing file " + fileName);

                    case ImPMTrace.FileChange.NewSuffix:
                        {
                            fileCountSuffix++;
                            continue;
                        }
                    case ImPMTrace.FileChange.NewName:
                        fileCountSuffix = 0;
                        break;
                }
            }
            return fileName;
        }

        internal static ImPMTraceSettings GetTraceSettings(Guid orgId)
        {
            return GetTraceSettings(orgId, true);
        }

        internal static ImPMTraceSettings GetTraceSettings(Guid orgId, bool create)
        {
            ImPMTraceSettings settings;
            bool flag = false;
            using (new ImPMLock(orgSettingsLock, LockMode.Read))
            {
                flag = orgSettings.TryGetValue(orgId, out settings);
            }
            if (!flag && create)
            {
                settings = new ImPMTraceSettings(1, orgId);
                SetTraceSetting(orgId, settings);
                return settings;
            }
            if (!flag && !create)
            {
                settings = new ImPMTraceSettings();
            }
            return settings;
        }

        //private static string GetTracingDirectory()
        //{
        //    string path = null;
        //    object obj2 = null;
        //    if (RegControl.IsInClientContext())
        //    {
        //        path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\MSCRM\Traces").ToString();
        //        if (!Directory.Exists(path))
        //        {
        //            Directory.CreateDirectory(path);
        //        }
        //        return path;
        //    }
        //    if (RegControl.IsInServerContext())
        //    {
        //        obj2 = RegistryCache.GetValue(RegControl.CrmServerInstallKeyDir);
        //        if ((obj2 != null) && (((string)obj2).Length != 0))
        //        {
        //            path = ((string)obj2) + @"\Trace";
        //        }
        //        return path;
        //    }
        //    string key = "TraceDirectory";
        //    obj2 = RegistryCache.GetValue(key);
        //    if ((obj2 != null) && (((string)obj2).Length != 0))
        //    {
        //        path = (string)obj2;
        //    }
        //    return path;
        //}

        public TraceLevel GetTracingLevel(TraceCategory traceCategory)
        {
            if (this._traceCategoryLevels == null)
            {
                this._traceCategoryLevels = GenerateTraceCategories("*:Error");
            }
            return (TraceLevel)this._traceCategoryLevels[traceCategory];
        }

        //internal static void Load()
        //{
        //    Load(null);
        //}

        //internal static void Load(string traceDirectory)
        //{
        //    ImPMTrace.TraceDisabled = true;
        //    if (RegControl.IsInServerContext())
        //    {
        //        try
        //        {
        //            LoadDeploymentSettings();
        //        }
        //        catch (Exception)
        //        {
        //            deploymentSettings = null;
        //        }
        //        try
        //        {
        //            LoadScaleGroupSettings();
        //        }
        //        catch (Exception)
        //        {
        //            siteWideSettings = null;
        //        }
        //    }
        //    try
        //    {
        //        LoadlocalServerRegistrySettings(traceDirectory);
        //    }
        //    catch (Exception)
        //    {
        //        localServerRegistrySettings = null;
        //    }
        //    ImPMTrace.TraceDisabled = false;
        //}

        //private static void LoadDeploymentSettings()
        //{
        //    ImPMTraceSettings settings = new ImPMTraceSettings();
        //    LocatorService service = new LocatorService();
        //    settings.IsTracingOff = !((bool)service.GetSiteSetting("TraceEnabled")) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //    settings.TracingCallStack = ((bool)service.GetSiteSetting("TraceCallStack")) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //    settings.TraceDirectory = ((string)service.GetSiteSetting("TraceDirectory")).Trim();
        //    string str = ((string)service.GetSiteSetting("TraceCategories")).Trim();
        //    if (string.IsNullOrEmpty(str))
        //    {
        //        settings._traceCategoryLevels = null;
        //    }
        //    else
        //    {
        //        settings._traceCategoryLevels = GenerateTraceCategories(str);
        //        if (settings._traceCategoryLevels == null)
        //        {
        //            settings._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //        }
        //    }
        //    settings.TraceFileSize = ((int)service.GetSiteSetting("TraceFileSize")) * 0x100000;
        //    settings.RefreshTraceInt = (int)service.GetSiteSetting("TraceRefresh");
        //    if (((settings != null) && (siteWideSettings != null)) && (siteWideSettings.RefreshTraceInt == settings.RefreshTraceInt))
        //    {
        //        settings.RefreshTraceInt = -1;
        //    }
        //    Interlocked.Exchange<ImPMTraceSettings>(ref siteWideSettings, settings);
        //}

        

        //private static void LoadScaleGroupSettings()
        //{
        //    LocatorService service = new LocatorService();
        //    if ((service.GetSku() != ConfigSku.Live) || (service.GetScaleGroupId() != Guid.Empty))
        //    {
        //        ImPMTraceSettings settings = new ImPMTraceSettings();
        //        settings.IsTracingOff = !((bool)service.GetDeploymentSetting("TraceEnabled")) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //        settings.TracingCallStack = ((bool)service.GetDeploymentSetting("TraceCallStack")) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //        settings.TraceDirectory = (string)service.GetDeploymentSetting("TraceDirectory");
        //        settings.TraceFileSize = ((int)service.GetDeploymentSetting("TraceFileSize")) * 0x100000;
        //        string deploymentSetting = (string)service.GetDeploymentSetting("TraceCategories");
        //        if (string.IsNullOrEmpty(deploymentSetting))
        //        {
        //            settings._traceCategoryLevels = null;
        //        }
        //        else
        //        {
        //            settings._traceCategoryLevels = GenerateTraceCategories(deploymentSetting);
        //            if (settings._traceCategoryLevels == null)
        //            {
        //                settings._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //            }
        //        }
        //        Interlocked.Exchange<ImPMTraceSettings>(ref deploymentSettings, settings);
        //    }
        //}

        //private void LoadSettingsFromConfigDB(int fileCountSuffix, Guid organizationId)
        //{
        //    this.FileCountSuffix = fileCountSuffix;
        //    this.LoadTraceEnabledFromDB(organizationId);
        //    this.LoadTraceDirectoryFromDB();
        //    this.LoadTraceFileSizeFromDB();
        //    this.LoadTraceCallStackFromDB(organizationId);
        //    this.LoadTraceCategoriesFromDB(organizationId);
        //    this.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulReported;
        //}

        //internal void LoadSettingsFromRegistry(int fileCountSuffix)
        //{
        //    this.LoadSettingsFromRegistry(fileCountSuffix, null);
        //}

        //internal void LoadSettingsFromRegistry(int fileCountSuffix, string traceDirectory)
        //{
        //    string str2;
        //    string key = string.Empty;
        //    DateTime now = DateTime.Now;
        //    this.LoadState = ImPMTrace.LoadStatus.LoadFailed;
        //    this.IsTracingOff = ImPMTrace.TraceBool.Unset;
        //    this.TracingCallStack = ImPMTrace.TraceBool.No;
        //    key = "TraceEnabled";
        //    if (RegistryCache.GetValue(key) == null)
        //    {
        //        this.IsTracingOff = ImPMTrace.TraceBool.Unset;
        //    }
        //    else
        //    {
        //        this.IsTracingOff = (((int)RegistryCache.GetValue("TraceEnabled", 0)) == 0) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //    }
        //    object obj2 = RegistryCache.GetValue("TraceRefresh");
        //    if (obj2 != null)
        //    {
        //        this.RefreshTraceInt = (int)obj2;
        //    }
        //    key = "TraceCallStack";
        //    obj2 = RegistryCache.GetValue(key);
        //    if (obj2 != null)
        //    {
        //        this.TracingCallStack = (((int)obj2) != 0) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //    }
        //    else
        //    {
        //        this.TracingCallStack = ImPMTrace.TraceBool.No;
        //    }
        //    if (traceDirectory == null)
        //    {
        //        this.TraceDirectory = GetTracingDirectory();
        //    }
        //    else
        //    {
        //        this.TraceDirectory = traceDirectory;
        //    }
        //    object obj3 = RegistryCache.GetValue("TraceFileSize");
        //    if (obj3 != null)
        //    {
        //        this.TraceFileSize = Convert.ToInt32(obj3, CultureInfo.InvariantCulture) * 0x100000;
        //    }
        //    if (this.TraceFileSize == 0)
        //    {
        //        this.TraceFileSize = 0xa00000;
        //    }
        //    this.FileCountSuffix = fileCountSuffix;
        //    key = "TraceCategories";
        //    obj2 = RegistryCache.GetValue("TraceCategories");
        //    if (obj2 != null)
        //    {
        //        str2 = (string)obj2;
        //    }
        //    else
        //    {
        //        str2 = "*:Error";
        //    }
        //    this._traceCategoryLevels = GenerateTraceCategories(str2);
        //    if (this._traceCategoryLevels == null)
        //    {
        //        this._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //    }
        //    this.LoadState = ImPMTrace.LoadStatus.LoadSuccessfulReported;
        //}

        //private void LoadTraceCallStackFromDB(Guid organizationId)
        //{
        //    if (((this._settingsPrecedence == SettingsPrecedence.Registry) && (localServerRegistrySettings != null)) && (localServerRegistrySettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
        //    {
        //        this.TracingCallStack = localServerRegistrySettings.TracingCallStack;
        //    }
        //    else if ((this._settingsPrecedence == SettingsPrecedence.Organization) && (organizationId != Guid.Empty))
        //    {
        //        LocatorService service = new LocatorService();
        //        PropertyBag bag = new PropertyBag();
        //        bag["Id"] = organizationId;
        //        string[] columns = new string[] { "Id", "TraceCallStack" };
        //        PropertyBag[] conditions = new PropertyBag[] { bag };
        //        PropertyBagCollection bags = service.Retrieve("Organization", columns, conditions);
        //        if ((bags != null) && (bags.Count > 0))
        //        {
        //            foreach (PropertyBag bag2 in bags.Values)
        //            {
        //                if (bag2["TraceCallStack"] != null)
        //                {
        //                    this.TracingCallStack = ((bool)bag2["TraceCallStack"]) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //    else if (((this._settingsPrecedence == SettingsPrecedence.Deployment) && (deploymentSettings != null)) && (deploymentSettings.TracingCallStack != ImPMTrace.TraceBool.Unset))
        //    {
        //        this.TracingCallStack = deploymentSettings.TracingCallStack;
        //    }
        //    else if (((this._settingsPrecedence == SettingsPrecedence.SiteWide) && (siteWideSettings != null)) && (siteWideSettings.TracingCallStack != ImPMTrace.TraceBool.Unset))
        //    {
        //        this.TracingCallStack = siteWideSettings.TracingCallStack;
        //    }
        //    else if (this._settingsPrecedence == SettingsPrecedence.Default)
        //    {
        //        this.TracingCallStack = ImPMTrace.TraceBool.No;
        //    }
        //}

        //private void LoadTraceCategoriesFromDB(Guid organizationId)
        //{
        //    string str = string.Empty;
        //    if (((this._settingsPrecedence == SettingsPrecedence.Registry) && (localServerRegistrySettings != null)) && (localServerRegistrySettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
        //    {
        //        this._traceCategoryLevels = localServerRegistrySettings._traceCategoryLevels;
        //        if (this._traceCategoryLevels == null)
        //        {
        //            this._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //        }
        //    }
        //    else if ((this._settingsPrecedence == SettingsPrecedence.Organization) && (organizationId != Guid.Empty))
        //    {
        //        LocatorService service = new LocatorService();
        //        PropertyBag bag = new PropertyBag();
        //        bag["Id"] = organizationId;
        //        string[] columns = new string[] { "Id", "TraceCategories" };
        //        PropertyBag[] conditions = new PropertyBag[] { bag };
        //        PropertyBagCollection bags = service.Retrieve("Organization", columns, conditions);
        //        if ((bags != null) && (bags.Count > 0))
        //        {
        //            foreach (PropertyBag bag2 in bags.Values)
        //            {
        //                str = (string)bag2["TraceCategories"];
        //                if (!string.IsNullOrEmpty(str))
        //                {
        //                    this._traceCategoryLevels = GenerateTraceCategories(str);
        //                    if (this._traceCategoryLevels == null)
        //                    {
        //                        this._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //                    }
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //    else if (((this._settingsPrecedence == SettingsPrecedence.Deployment) && (deploymentSettings != null)) && (string.IsNullOrEmpty(str) && (deploymentSettings._traceCategoryLevels != null)))
        //    {
        //        this._traceCategoryLevels = deploymentSettings._traceCategoryLevels;
        //        if (this._traceCategoryLevels == null)
        //        {
        //            this._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //        }
        //    }
        //    else if (((this._settingsPrecedence == SettingsPrecedence.SiteWide) && (siteWideSettings != null)) && (string.IsNullOrEmpty(str) && (siteWideSettings._traceCategoryLevels != null)))
        //    {
        //        this._traceCategoryLevels = siteWideSettings._traceCategoryLevels;
        //        if (this._traceCategoryLevels == null)
        //        {
        //            this._traceCategoryLevels = GenerateTraceCategories("*:Error");
        //        }
        //    }
        //    else if (this._settingsPrecedence == SettingsPrecedence.Default)
        //    {
        //        str = "*:Error";
        //        this._traceCategoryLevels = GenerateTraceCategories(str);
        //    }
        //}

        private void LoadTraceDirectoryFromDB()
        {
            if (((this._settingsPrecedence == SettingsPrecedence.Registry) && (localServerRegistrySettings != null)) && (localServerRegistrySettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
            {
                this.TraceDirectory = localServerRegistrySettings.TraceDirectory;
            }
            else if (((this._settingsPrecedence == SettingsPrecedence.Deployment) || (this._settingsPrecedence == SettingsPrecedence.Organization)) && ((deploymentSettings != null) && (deploymentSettings.TraceDirectory != null)))
            {
                this.TraceDirectory = deploymentSettings.TraceDirectory;
            }
            else if (((this._settingsPrecedence == SettingsPrecedence.SiteWide) && (siteWideSettings != null)) && (siteWideSettings.TraceDirectory != null))
            {
                this.TraceDirectory = siteWideSettings.TraceDirectory;
            }
            else if (this._settingsPrecedence == SettingsPrecedence.Default)
            {
                this.IsTracingOff = ImPMTrace.TraceBool.Yes;
                this.TraceDirectory = null;
            }
        }

        //private void LoadTraceEnabledFromDB(Guid organizationId)
        //{
        //    if (((localServerRegistrySettings != null) && (localServerRegistrySettings.IsTracingOff != ImPMTrace.TraceBool.Unset)) && (localServerRegistrySettings.IsTracingOff == ImPMTrace.TraceBool.No))
        //    {
        //        this.IsTracingOff = localServerRegistrySettings.IsTracingOff;
        //        this._settingsPrecedence = SettingsPrecedence.Registry;
        //    }
        //    if (organizationId != Guid.Empty)
        //    {
        //        LocatorService service = new LocatorService();
        //        PropertyBag bag = new PropertyBag();
        //        bag["Id"] = organizationId;
        //        string[] columns = new string[] { "Id", "TraceEnabled" };
        //        PropertyBag[] conditions = new PropertyBag[] { bag };
        //        PropertyBagCollection bags = service.Retrieve("Organization", columns, conditions);
        //        if ((bags != null) && (bags.Count > 0))
        //        {
        //            foreach (PropertyBag bag2 in bags.Values)
        //            {
        //                if (bag2["TraceEnabled"] != null)
        //                {
        //                    ImPMTrace.TraceBool @bool = !((bool)bag2["TraceEnabled"]) ? ImPMTrace.TraceBool.Yes : ImPMTrace.TraceBool.No;
        //                    if (@bool == ImPMTrace.TraceBool.No)
        //                    {
        //                        this.IsTracingOff = @bool;
        //                        this._settingsPrecedence = SettingsPrecedence.Organization;
        //                    }
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //    else if ((deploymentSettings != null) && (deploymentSettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
        //    {
        //        if (deploymentSettings.IsTracingOff == ImPMTrace.TraceBool.No)
        //        {
        //            this.IsTracingOff = deploymentSettings.IsTracingOff;
        //            this._settingsPrecedence = SettingsPrecedence.Deployment;
        //        }
        //    }
        //    else if ((siteWideSettings != null) && (siteWideSettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
        //    {
        //        if (siteWideSettings.IsTracingOff == ImPMTrace.TraceBool.No)
        //        {
        //            this.IsTracingOff = siteWideSettings.IsTracingOff;
        //            this._settingsPrecedence = SettingsPrecedence.SiteWide;
        //        }
        //    }
        //    else if (this._settingsPrecedence == SettingsPrecedence.Default)
        //    {
        //        this.IsTracingOff = ImPMTrace.TraceBool.Yes;
        //        this._settingsPrecedence = SettingsPrecedence.Default;
        //    }
        //}

        private void LoadTraceFileSizeFromDB()
        {
            if (((this._settingsPrecedence == SettingsPrecedence.Registry) && (localServerRegistrySettings != null)) && (localServerRegistrySettings.IsTracingOff != ImPMTrace.TraceBool.Unset))
            {
                this.TraceFileSize = localServerRegistrySettings.TraceFileSize;
            }
            else if (((this._settingsPrecedence == SettingsPrecedence.Deployment) || (this._settingsPrecedence == SettingsPrecedence.Organization)) && ((deploymentSettings != null) && (deploymentSettings.TraceFileSize != 0)))
            {
                this.TraceFileSize = deploymentSettings.TraceFileSize;
            }
            else if (((this._settingsPrecedence == SettingsPrecedence.SiteWide) && (siteWideSettings != null)) && (siteWideSettings.TraceFileSize != 0))
            {
                this.TraceFileSize = siteWideSettings.TraceFileSize;
            }
            else if (this._settingsPrecedence == SettingsPrecedence.Default)
            {
                this.TraceFileSize = 0xa00000;
            }
        }

        internal static void PurgeTraceSettings()
        {
            using (new ImPMLock(orgSettingsLock, LockMode.Write))
            {
                orgSettings = null;
                orgSettings = new Dictionary<Guid, ImPMTraceSettings>();
            }
        }

        //public void SetTextWriter()
        //{
        //    ImPMTrace.Assert(readerWriterLock.IsWriterLockHeld, "SetTextWriter must be called from within a Write Lock");
        //    try
        //    {
        //        using (new AutoReimpersonator())
        //        {
        //            StreamWriter writer = new StreamWriter(File.Open(this.FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
        //            writer.AutoFlush = true;
        //            if (ImPMTraceSettings.writer != null)
        //            {
        //                ImPMTraceSettings.writer.Close();
        //                ImPMTraceSettings.writer = null;
        //            }
        //            ImPMTraceSettings.writer = TextWriter.Synchronized(writer);
        //        }
        //    }
        //    catch (IOException)
        //    {
        //        ImPMTrace.WriteEventError(0xc0004304L, new string[] { this.FileName });
        //        ImPMTraceSettings.writer = null;
        //    }
        //    catch (ArgumentException)
        //    {
        //        ImPMTrace.WriteEventError(0xc0004304L, new string[] { this.FileName });
        //        ImPMTraceSettings.writer = null;
        //    }
        //    catch (UnauthorizedAccessException)
        //    {
        //        ImPMTrace.WriteEventError(0xc0004304L, new string[] { this.FileName });
        //        ImPMTraceSettings.writer = null;
        //    }
        //    catch (NotSupportedException)
        //    {
        //        ImPMTrace.WriteEventError(0xc0004304L, new string[] { this.FileName });
        //        ImPMTraceSettings.writer = null;
        //    }
        //}

        internal static void SetTraceSetting(Guid orgId, ImPMTraceSettings setting)
        {
            using (new ImPMLock(orgSettingsLock, LockMode.Write))
            {
                if (!orgSettings.ContainsKey(orgId))
                {
                    orgSettings.Add(orgId, setting);
                }
                else
                {
                    orgSettings[orgId] = setting;
                }
            }
        }

        // Properties
        public int FileCountSuffix
        {
            get
            {
                return this._fileCountSuffix;
            }
            set
            {
                this._fileCountSuffix = value;
            }
        }

        public string FileName
        {
            get
            {
                return this._fileName;
            }
            set
            {
                this._fileName = value;
            }
        }

        public ImPMTrace.TraceBool IsTracingOff
        {
            get
            {
                return this._isTracingOff;
            }
            set
            {
                this._isTracingOff = value;
            }
        }

        public ImPMTrace.LoadStatus LoadState
        {
            get
            {
                return this._loadState;
            }
            set
            {
                this._loadState = value;
            }
        }

        public int RefreshTraceInt
        {
            get
            {
                return this._refreshTraceInt;
            }
            set
            {
                this._refreshTraceInt = value;
            }
        }

        public static int RegistryRefreshTraceInt
        {
            get
            {
                if (localServerRegistrySettings != null)
                {
                    return localServerRegistrySettings.RefreshTraceInt;
                }
                return -1;
            }
        }

        public static int SiteWideRefreshTraceInt
        {
            get
            {
                if (siteWideSettings != null)
                {
                    return siteWideSettings.RefreshTraceInt;
                }
                return -1;
            }
        }

        public Hashtable TraceCategoryLevels
        {
            get
            {
                return this._traceCategoryLevels;
            }
        }

        public string TraceDirectory
        {
            get
            {
                return this._traceDirectory;
            }
            set
            {
                this._traceDirectory = value;
            }
        }

        public int TraceFileSize
        {
            get
            {
                return this._traceFileSize;
            }
            set
            {
                this._traceFileSize = value;
            }
        }

        public ImPMTrace.TraceBool TracingCallStack
        {
            get
            {
                return this._tracingCallStack;
            }
            set
            {
                this._tracingCallStack = value;
            }
        }

        public static TextWriter Writer
        {
            get
            {
                return writer;
            }
        }
    }


}
